package cn.itlb.servlet;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.itlb.vo.ImageItem;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

@WebServlet("/serch")
public class ImgServlet extends HttpServlet {

	Log log = LogFactory.getLog(this.getClass());

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String q = request.getParameter("q");
		int sn = 50;
		int pn = 50;
		String url = "http://image.so.com/j?q=%s&src=srp&correct=%s&sn=%d&pn=%d";
		q = URLEncoder.encode(q, "utf-8");//编码
		url = String.format(url, q, q, sn, pn);

		OkHttpClient client = new OkHttpClient();
		Request req = new Request.Builder().url(url).build();

		Response res = client.newCall(req).execute();
		String json=res.body().string();
		//log.info(json);
		//解析json
		JSONObject jsonObject =JSONObject.parseObject(json);
		Integer total=jsonObject.getIntValue("total");//取json中的total,lastindex,list
		Integer lastindex=jsonObject.getInteger("lastindex");
		JSONArray jsonArrayList=jsonObject.getJSONArray("list");
		
		List<ImageItem> images=new ArrayList<>();
		  for(int i=0;i<jsonArrayList.size();i++){
			  
			 // ImageItem item=JSON.parseObject(jsonArrayList.get(i).toString(),ImageItem.class);
			 // images.add(item);
			 // log.info(item.getImg());

			 JSONObject obj=(JSONObject)jsonArrayList.get(i);
			//  log.info(obj.toJSONString());
			ImageItem item=JSON.parseObject(obj.toJSONString(),ImageItem.class);
			  //ImageItem item=obj.toJavaObject(ImageItem.class);
			 // ImageItem item=new ImageItem();
			 // log.info(obj.getString("thumb"));
			  //item.setImg(obj.getString("thumb"));
			 // item.setThumb(obj.getString("thumb"));			  						  
			images.add(item);
			log.info(item.getImg());
		  }
		 request.setAttribute("images", images); 
		 request.getRequestDispatcher("index.jsp").forward(request, response);
	}

}
